package vn.com.hung.notetaker.book.forms;


import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.io.IOException;
import java.util.Vector;

import javax.swing.GroupLayout;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.GroupLayout.Alignment;

import vn.com.hung.notetaker.abstractMenus.NoteViewMenu;
import vn.com.hung.notetaker.abstractMenus.TableSelectedPopupMenu;
import vn.com.hung.notetaker.book.datamodels.BookViewTableModel;
import vn.com.hung.notetaker.datatypes.BookRecord;
import vn.com.hung.notetaker.utils.DialogDisplayer;


@SuppressWarnings("serial")
public class BookListViewForm extends JFrame implements ActionListener { 
    
    private NoteViewMenu menu;
    private JTable bookTable = new JTable();
    private JButton addButton = new JButton("Add Book");
    private JButton openButton = new JButton("Open");
    private JButton saveButton = new JButton("Save");
    private BNTakerFrame frame = null;
    
    public BookListViewForm() {
        setTitle("Book Note Taker 1.0 @ Hunglv");
        menu = new NoteViewMenu(bookTable);
        setJMenuBar(menu);
        addButton.setName("add");
        addButton.addActionListener(this);
        openButton.setName("open");
        openButton.addActionListener(this);
        saveButton.setName("save");
        saveButton.addActionListener(this);
       
        BookViewTableModel model = new BookViewTableModel();
        bookTable.setModel(model);
        JScrollPane scrollPane = new JScrollPane(bookTable);
        bookTable.addMouseListener(new BookTableMouseListener());
        
        GroupLayout layout = new GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setAutoCreateContainerGaps(true);
        layout.setAutoCreateGaps(true);
        
        layout.setHorizontalGroup(layout.createParallelGroup(Alignment.LEADING)
                .addComponent(scrollPane)
                .addGroup(layout.createSequentialGroup()
                        .addComponent(addButton)
                        .addComponent(openButton)
                        .addComponent(saveButton)));
        layout.setVerticalGroup(layout.createSequentialGroup()
                .addComponent(scrollPane)
                .addGroup(layout.createParallelGroup(Alignment.BASELINE)
                        .addComponent(addButton)
                        .addComponent(openButton)
                        .addComponent(saveButton)));
        
        pack();
        setDefaultCloseOperation(DISPOSE_ON_CLOSE);
    }
    
    public static void main(String[] args) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
                BookListViewForm note = new BookListViewForm();
                note.setVisible(true);
                note.addWindowListener(new WindowListener() {
                    
                    @Override
                    public void windowOpened(WindowEvent arg0) { }
                    
                    @Override
                    public void windowIconified(WindowEvent arg0) { }
                    
                    @Override
                    public void windowDeiconified(WindowEvent arg0) { }
                    
                    @Override
                    public void windowDeactivated(WindowEvent arg0) { }
                    
                    @Override
                    public void windowClosing(WindowEvent arg0) { 
//                        JFrame frame = new JFrame();
//
//                        JOptionPane.showConfirmDialog(frame,
//                                "Some Data has not been save! \n"
//                                        + "Do you want to save your data",
//                                "Error", JOptionPane.INFORMATION_MESSAGE);
//                        frame.pack();
//                        frame.setResizable(false);
//                        frame.setVisible(true);
//                        frame.setLocation(500, 200);
//                        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
                    }

                    @Override
                    public void windowClosed(WindowEvent e) {
                        
                    }
                    
                    @Override
                    public void windowActivated(WindowEvent arg0) { }
                });
            }
        });
    }
    
    private class BookTableMouseListener extends MouseAdapter {
        public void mouseClicked(MouseEvent e) {
            if (SwingUtilities.isLeftMouseButton(e)) {
               
            } else if (SwingUtilities.isRightMouseButton(e)) {
                Point p = e.getPoint();
                int row = bookTable.rowAtPoint(p);
                int column = bookTable.columnAtPoint(p);
                if (row == bookTable.getSelectedRow()) {
                    TableSelectedPopupMenu pmenu = new TableSelectedPopupMenu(bookTable);                
                    pmenu.show(e.getComponent(), e.getX(), e.getY());
                }
            }
        }
    }
    
    @Override
    public void actionPerformed(ActionEvent arg0) {
        String name = ((JComponent) arg0.getSource()).getName();
        // add button pressed
        if (name.equalsIgnoreCase(addButton.getName())) {
            new AddBookForm(bookTable);
        } else if (name.equalsIgnoreCase(saveButton.getName())) {
            BookViewTableModel model = (BookViewTableModel) bookTable
                    .getModel();
            try {
                model.saveToCSV(model.getModelFilePath());
                DialogDisplayer.showDefaultInforDialog("Save Done");
            } catch (Exception e1) {
                DialogDisplayer.showDefaultErrorDialog("Save Fail");
            }

        } else if (name.equals(openButton.getName())) {
            
            int row = bookTable.getSelectedRow();
            if (row == -1) {
                return;
            }
            Vector<Object> rowData = ((BookViewTableModel) bookTable.getModel()).getRowData(row);
            String bookName = rowData.get(0).toString();
            String bookAuthor = rowData.get(1).toString();
            if (bookName.length() < 2) {
                DialogDisplayer.showDefaultErrorDialog("Please add a book");
                return;
            }
            BookRecord book = new BookRecord(bookName,bookAuthor);
            if (frame == null) {
                frame = new BNTakerFrame(book);
                frame.setVisible(true);
            } else {
                    if (!frame.isVisible()) {
                        frame = new BNTakerFrame(book);
                        frame.setVisible(true);
                    } else {
                        frame.addBookNoteTaker(book);
                    }
            }
        }
    }
    
    public void loadBookList(String path) {
        try {
            ((BookViewTableModel) bookTable.getModel()).loadCSV(path);
            bookTable.updateUI();
        } catch (IOException e) {
            DialogDisplayer.showDefaultErrorDialog("Cannot Load Data");
        }
       
    }
    
    public void addBook(BookRecord book) {
        Vector<Object> rowData = new Vector<Object>();
        rowData.add(book.getName());
        rowData.add(book.getAuthor());
        rowData.add(book.getStatus());
        ((BookViewTableModel) bookTable.getModel()).addRow(rowData, bookTable.getRowCount());
        
    }
    
}
